package com.ycsj.goldmedalnewconcept.adapter;

import android.content.Context;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.MusicInfo;

/**
 * 创建日期：2017/11/12 9:17 描述:音乐播放列表的适配器 作者:张伟
 */

public class MusicAdapter extends CommonAdapter<MusicInfo> {
	private Context context;
	// 音乐播放器对象
	private MediaPlayer player;

	private List<MusicInfo> datas;

	public MusicAdapter(Context context, List<MusicInfo> datas, int layoutId) {
		super(context, datas, layoutId);
		this.context = context;
		this.datas = datas;
	}

	@Override
	public void convert(ViewHolder holder, final MusicInfo musicInfo) {
		// 音乐名称
		TextView tvMusicName = holder.getView(R.id.tv_music_name);
		tvMusicName.setText(musicInfo.getName());
		// 播放状态
		ImageView lvState = holder.getView(R.id.lv_state);
		if (musicInfo.isPlaying()) {
			lvState.setImageResource(R.drawable.pause);
		} else {
			lvState.setImageResource(R.drawable.play);
		}
		RelativeLayout rlState = holder.getView(R.id.rl_state);
		// 播放按钮的点击事件
		rlState.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
					
				//首先改变当前条目的图标状态
				for (int i = 0; i < datas.size(); i++) {
					if (datas.get(i) != musicInfo) {
						datas.get(i).setPlaying(false);
					} else {
						musicInfo.setPlaying(!musicInfo.isPlaying());
					}
				}

				notifyDataSetChanged();
				
				//根据播放状态的进行播放	
				if (null != player && player.isPlaying()) {
					// 播放状态
					player.stop();
//					musicInfo.setPlaying(false);
//					// 同时要讲所有其它的状态设置为false
//					for (int i = 0; i < datas.size(); i++) {
//						datas.get(i).setPlaying(false);
//					}
//
//					notifyDataSetChanged();

				} else {
					// 非播放状态
					// 如果当前的状态是没有播放就进行下面的操作
					if (null == player) {
						// 如果播放器为null,就创建一个播放器
						player = MediaPlayer.create(context,
								musicInfo.getResId());
					} else {
						player.reset();
						player = MediaPlayer.create(context,
								musicInfo.getResId());
					}

					player.start();

//					musicInfo.setPlaying(true);
//
//					for (int i = 0; i < datas.size(); i++) {
//						if (datas.get(i) != musicInfo) {
//							datas.get(i).setPlaying(false);
//						}
//					}
//
//					notifyDataSetChanged();
				}

				
				
				player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mediaPlayer) {
						musicInfo.setPlaying(false);
						notifyDataSetChanged();
					}
				});
			}
		});
	}
}
